﻿Imports System.ComponentModel

Public NotInheritable Class MailManager

    Private Shared _settings As MailSettings
    Public Shared Sub SetSettings(ByVal settings As MailSettings)
        _settings = settings
    End Sub

    Private Sub New()
    End Sub

    Private Shared Sub MailSend_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
        Try
            Dim obj = DirectCast(e.Argument, Object())
            DirectCast(obj(0), System.Net.Mail.SmtpClient).Send(DirectCast(obj(1), System.Net.Mail.MailMessage))
        Catch ex As Exception
#If DEBUG Then
            Stop
#End If
        End Try
    End Sub

    Public Shared Sub Send(ByVal title As String, ByVal body As String, ByVal toAddress As String, ByVal fromAddress As String, ByVal smtpServer As String, ByVal port As Integer, ByVal encoding As String, ByVal enableSsl As Boolean, ByVal userName As String, ByVal password As String)

        Dim msg As New System.Net.Mail.MailMessage()
        Dim enc = System.Text.Encoding.GetEncoding(encoding)
        Try
            msg.SubjectEncoding = enc
            msg.BodyEncoding = enc
            msg.From = New System.Net.Mail.MailAddress(fromAddress, My.Resources.ApplicationName, enc)
            msg.To.Add(New System.Net.Mail.MailAddress(toAddress, toAddress, enc))

            msg.Subject = title
            msg.Body = body

            Dim client = New System.Net.Mail.SmtpClient()
            client.Host = smtpServer
            client.Port = port
            client.EnableSsl = enableSsl

            'ユーザー名とパスワードを設定する
            If userName <> "" Then
                client.Credentials = New System.Net.NetworkCredential(userName, password.Decrypt)
            End If

            ' Send
            Dim worker = New BackgroundWorker
            AddHandler worker.DoWork, AddressOf MailSend_DoWork
            worker.RunWorkerAsync(New Object() {client, msg})

        Catch ex As Exception
#If DEBUG Then
            Stop
#End If
        End Try

    End Sub

    Public Shared Sub Send(ByVal title As String, ByVal body As String)

        Send(title, body, _settings.ToAddress, _settings.FromAddress, _settings.SmtpServer, _settings.Port, _settings.Encoding, _settings.EnableSsl, _settings.UserName, _settings.Password)

    End Sub

End Class

